import React, { memo, useEffect, useRef } from 'react';

import Scroll from '../scroll';
import { PropTypes } from 'prop-types';
import { List, ListItem } from './style';

const Horizon = memo(function (props) {
  const { list, oldVal, title } = props;
  const { handleClick } = props;
  const categoryRef = useRef(null);
  // 初始化内容宽度的逻辑
  useEffect(() => {
    const categoryDom = categoryRef.current;
    const tagElems = categoryDom.querySelectorAll('span');
    let totalWidth = 0;
    Array.from(tagElems).forEach((ele) => {
      totalWidth += ele.offsetWidth;
    });
    categoryDom.style.width = `${totalWidth}px`;
  }, []);

  return (
    <Scroll direction={'horizontal'}>
      <div ref={categoryRef}>
        <List>
          <span>{title}</span>
          {list.map((item) => (
            <ListItem
              key={item.key}
              className={`${oldVal === item.key ? 'selected' : ''}`}
              onClick={() => {
                handleClick(item);
              }}
            >
              {item.name}
            </ListItem>
          ))}
        </List>
      </div>
    </Scroll>
  );
});

Horizon.defaultProps = {
  list: [], //list 为接受的列表数据
  oldVal: '', // 当前item的值
  title: '', // 为列表左边的标题
  handleClick: null, //handleClick 为点击不同的 item 执行的方法
};
Horizon.propTypes = {
  list: PropTypes.array,
  oldVal: PropTypes.string,
  title: PropTypes.string,
  handleClick: PropTypes.func,
};
export default Horizon;
